package com.com.designpatterns.visitor;

import java.util.logging.Logger;

/**
 * Created by pankaj on 7/11/15.
 */
public abstract class Tree<E> {
    static Logger logger = Logger.getLogger(Tree.class.getName());

    static {
        logger.setParent(Logger.getLogger(Tree.class.getPackage().getName()));
    }
    abstract public String toString();
    abstract public Double sum();

    public static <E> Tree<E> leaf(E e){
        return new Tree<E>(){
            @Override
            public String toString() {
                return e.toString();
            }

            @Override
            public Double sum() {
                return ((Number) e).doubleValue();
            }
        };
    }

    public static <E> Tree<E> branch(Tree<E> l, Tree<E> r)
    {
        return new Tree<E>(){
            @Override
            public String toString() {
                return "("+l.toString() + " ^ " + r.toString()+")";
            }

            @Override
            public Double sum() {
                return l.sum() * r.sum();
            }
        };
    }
}

class TreeClient{
    static Logger logger = Logger.getLogger(Tree.class.getName());

    static {
        logger.setParent(Logger.getLogger(Tree.class.getPackage().getName()));
    }
    public static void main(String[] args) {
        Tree<Integer> t = Tree.branch(Tree.leaf(2), Tree.leaf(4));
        System.out.println("t.toString() = " +t.toString());
        System.out.println("t.sum = " + t.sum());

        Tree<Double> d = Tree.branch(Tree.branch(Tree.leaf(4.0), Tree.leaf(5.0)), Tree.leaf(7.0));
        logger.info(d.sum().toString());
        logger.info(d.toString());
    }
}
